import { getList } from '@/api/quanxian'


const getDefaultState = () => {
  return {
    quanxian: [],
    name: '',
    avatar: ''
  }
}

const state = getDefaultState()

const mutations = {
   SET_QUANXIAN: (state, quanxian) => {
    state.quanxian = quanxian
  }
}

const actions = {
  // user login
  getList({ commit }, userInfo) {
     
    return new Promise((resolve, reject) => {
    getList(userInfo).then(response => {
        const { data } = response
        commit('SET_QUANXIAN', data)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response

        if (!data) {
          reject('Verification failed, please Login again.')
        }

        const { name, avatar } = data

        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

